<template>
  <div class="pad-20 bgc-default">
    <div class="pad-l-20 pad-r-20 pad-t-15 bg-color-white">
      <!--顶部搜索 -->
      <div class="top-operate">
        <div class="search-item">
          <label class="mar-l-20">商品搜索：</label>
          <el-input
            @keyup.enter.native="handleSearch"
            v-model="searchKeyword"
            placeholder="请输入关键词"
          ></el-input>
          <el-button-group>
            <el-button class="mar-l-20" type="primary" @click="handleSearch"
              >查询</el-button
            >
            <el-button @click="resetClick">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <!--商品状态 -->
      <div class="tabs-box mar-b-15 mar-t-15">
        <el-tabs
          type="card"
          v-model="auditStatus"
          @tab-click="auditStatusCilck"
        >
          <el-tab-pane :label="waitName" name="0"></el-tab-pane>
          <el-tab-pane :label="inName" name="1"></el-tab-pane>
          <el-tab-pane :label="passName" name="2"></el-tab-pane>
          <el-tab-pane :label="noPassName" name="3"></el-tab-pane>
          <el-tab-pane :label="allName" name="4"></el-tab-pane>
        </el-tabs>
      </div>
      <div v-if="auditStatus === '1'" class="pad-b-15">
        <el-button type="primary" @click="saveSynchronousAudit"
          >同步审核进度</el-button
        >
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table
          ref="multipleTable"
          :data="goodsList"
          @selection-change="handleSelectionChange"
          v-loading="listLoading"
          element-loading-text="加载中"
          style="width: 100%"
          header-cell-class-name="default-header"
          row-class-name="default-row"
        >
          <el-table-column width="400px" label="基本信息" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p" @click="handleEdit(scope.row, '0')">
                <label><img :src="scope.row.goodsImgUrl" class="user-avatar cursor-p"/></label>
                <div class="font-14 pad-l-10 goods-title">
                  <div>{{ scope.row.title }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="价格">
            <template slot-scope="scope">
              <span v-if="scope.row.priceType === 1">￥{{ scope.row.price }}</span>
              <span v-if="scope.row.priceType === 2">￥{{ scope.row.minPrice }}~￥{{ scope.row.maxPrice }}</span>
              <span v-if="scope.row.priceType === 3">
                <span>原价￥{{ scope.row.originalPrice }}元</span><br />
                <span>现价￥{{ scope.row.nowPrice }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column
            width="620px"
            label="链接"
            prop="goodsMiniUrl"
          ></el-table-column>
          <el-table-column width="120px" label="状态">
            <template slot-scope="scope">
              {{ dict.auditStatus[scope.row.auditStatus] }}
            </template>
          </el-table-column>
          <el-table-column
            width="280px"
            label="操作"
            align="right"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="medium"
                @click="liveGoodsJoin(scope.row, 1)"
                v-if="
                  scope.row.auditStatus === 0 || scope.row.auditStatus === 3
                "
                >提交审核</el-button
              >
              <el-button
                type="text"
                size="medium"
                @click="handleEdit(scope.row, '0')"
                v-if="
                  scope.row.auditStatus === 0 || scope.row.auditStatus === 3
                "
                >编辑</el-button
              >
              <el-button
                type="text"
                size="medium"
                @click="liveGoodsJoin(scope.row, 2)"
                v-if="scope.row.auditStatus === 1"
                >撤回审核</el-button
              >
              <el-button
                type="text"
                size="medium"
                @click="handleEdit(scope.row, '2')"
                v-if="scope.row.auditStatus === 2"
                >修改价格</el-button
              >
              <el-button
                type="text"
                size="medium"
                @click="liveGoodsDelete(scope.row)"
                v-if="
                  scope.row.auditStatus === 0 ||
                  scope.row.auditStatus === 2 ||
                  scope.row.auditStatus === 3
                "
                >移出商品库</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title=""
      v-el-drag-dialog
      :visible.sync="liveGoodsVisible"
      :close-on-press-escape="true"
      :center="true"
      width="850px"
    >
      <el-form :model="liveGoods" label-position="right" label-width="120px">
        <el-form-item label="商品封面">
          <el-upload
            list-type="picture-card"
            action="/api/common/uploadFiles"
            accept="image/jpeg,image/gif,image/png,image/bmp"
            name="files"
            :data="token"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img
              v-if="liveGoods.goodsImgUrl"
              :src="liveGoods.goodsImgUrl"
              width="148px"
              height="148px"
              style="margin-left: -1px; margin-top: -1px"
            />
            <i v-else class="el-icon-plus"></i>
          </el-upload>
          <span>建议尺寸：200像素 * 200像素，图片大小不得超过50K。</span>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            v-model="liveGoods.title"
            class="width-per-70"
            placeholder="请输商品名称"
            :disabled="titleVisible"
          ></el-input
          ><br />
          <span
            >商品名称必须为3-14个汉字（一个字等于两个英文字符或特殊字符）</span
          >
        </el-form-item>
        <el-form-item label="价格形式">
          <el-radio-group v-model="priceType">
            <el-radio v-if="liveGoods.skuFlag == 0" label="1" class="mar-b-10">
              <span class="width-100 display-inline">一口价</span>
              <span>价格</span>
              <el-input
                v-model="liveGoods.price"
                class="width-180"
                type="number"
              >
                <template slot="append">元</template>
              </el-input> </el-radio
            ><br />
            <el-radio v-if="liveGoods.skuFlag == 1" label="2" class="mar-b-10">
              <span class="width-100 display-inline">价格区间</span>
              <span>价格</span>
              <el-input v-model="liveGoods.minPrice" class="width-180">
                <template slot="append">元</template>
              </el-input>
              <span class="width-20 display-inline text-align-c">-</span>
              <el-input
                v-model="liveGoods.maxPrice"
                class="width-180"
                type="number"
              >
                <template slot="append">元</template>
              </el-input> </el-radio
            ><br />
            <el-radio
              v-if="
                liveGoods.skuFlag == 0 
              "
              label="3"
              class="mar-b-10"
            >  
              <span class="width-100 display-inline">显示折扣价</span>
              <span>原价</span>
              <el-input v-model="liveGoods.originalPrice" class="width-180">
                <template slot="append">元</template>
              </el-input>
              <span class="width-20 display-inline text-align-c"></span>
              <span>现价</span>
              <el-input
                v-model="liveGoods.nowPrice"
                class="width-180"
                type="number"
              >
                <template slot="append">元</template>
              </el-input>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="flex flex-center pad-t-24">
        <el-button class="width-110" @click="liveGoodsVisible = false"
          >取消</el-button
        >
        <template v-if="joinType === '0'">
          <el-button type="primary" class="width-110" @click="addLiveGoods(0)"
            >保存</el-button
          >
          <el-button type="primary" class="width-110" @click="addLiveGoods(1)"
            >保存并审核</el-button
          >
        </template>
        <template v-else>
          <el-button type="primary" class="width-110" @click="addLiveGoods(2)"
            >保存</el-button
          >
        </template>
        
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  pageLiveGoods,
  liveGoodsDelete,
  saveProjectLiveGoods,
  saveSynchronousAudit,
  getLiveGoods,
  addLiveGoods,
  doApplyGoodsPrice,
  countLiveGoods
} from '@/api/goods/liveGoods'
import { getToken } from '@/utils/auth'
import elDragDialog from '@/directive/el-dragDialog'

export default {
  directives: {
    elDragDialog
  },
  data() {
    return {
      total: null,
      joinType: '0',
      multipleSelection: [],
      listLoading: true,
      searchListQuery: {
        enterpriseId: this.getEnterpriseId(),
        supplierId: this.getSupplierId(),
        currentPage: 1,
        size: 10,
        title: ''
      },
      priceType: '1',
      liveGoods: {
        liveGoodsId: '',
        goodsImgUrl: '',
        priceType: '1',
        price: '',
        minPrice: '',
        maxPrice: '',
        originalPrice: '',
        nowPrice: '',
        auditStatus: '0',
        goodsId: '',
        enterpriseId: this.getEnterpriseId()
      },
      liveGoodsVisible: false,
      titleVisible: false,
      searchKeyword: '',
      dict: {},
      auditStatus: '0',
      goodsList: [],
      waitName: '待审核',
      inName: '审核中',
      passName: '审核通过',
      noPassName: '审核未通过',
      allName: '全部'
    }
  },
  // 初始化页面
  created() {
    this.token = { accessToken: getToken() }
    this.initGoodsList()
  },
  filters: {
    priceFilter(e) {
      return e.toFixed(2)
    }
  },
  mounted() {},
  methods: {
    initCount() {
      const date = {
        enterpriseId: this.getEnterpriseId(),
        title: this.searchKeyword
      }
      countLiveGoods(date).then((response) => {
        if (response.isError) return
        this.waitName = '待审核(' + response.data.waitNum + ')'
        this.inName = '审核中(' + response.data.inNum + ')'
        this.passName = '审核通过(' + response.data.passNum + ')'
        this.noPassName = '审核未通过(' + response.data.noPassNum + ')'
        this.allName = '全部(' + response.data.allNum + ')'
      })
    },
    // 更改当前页数
    handleCurrentChange(val) {
      this.searchListQuery.currentPage = val
      this.initGoodsList()
    },
    auditStatusCilck() {
      this.initGoodsList()
    },
    liveGoodsJoin(row, liveGoodsType) {
      saveProjectLiveGoods(
        row.liveGoodsId,
        liveGoodsType,
        this.getEnterpriseId()
      ).then((response) => {
        if (response.isError) return
        this.$message({
          message: '成功',
          type: 'success'
        })
        this.initGoodsList()
      })
    },
    saveSynchronousAudit() {
      saveSynchronousAudit(this.getEnterpriseId()).then((response) => {
        if (response.isError) return
        this.$message({
          message: '成功',
          type: 'success'
        })
        this.initGoodsList()
      })
    },
    liveGoodsDelete(row, auditStatus) {
      if (
        row.auditStatus === 0 ||
        row.auditStatus === 2 ||
        row.auditStatus === 3
      ) {
        let remark = '确定要将商品移出直播商品库？'
        if (row.auditStatus === 2) {
          remark = '此商品将从所有直播间中同时删除，且不可恢复，确定要移出吗？'
        }
        this.$confirm(remark, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            liveGoodsDelete(row.liveGoodsId).then((response) => {
              if (response.isError) return
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.initGoodsList()
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      }
      if (row.auditStatus === 1) {
        this.$alert('商品库审核中的商品不允许移出。', '', {
          confirmButtonText: '关闭'
        })
      }
    },
    // 更改当前页面大小
    handleSizeChange(val) {
      this.searchListQuery.size = val
      this.initGoodsList()
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    initGoodsList() {
      this.initCount()
      this.listLoading = true
      this.searchListQuery['title'] = this.searchKeyword
      // 搜索状态
      if (this.auditStatus === '4') {
        this.searchListQuery['auditStatus'] = ''
      } else {
        this.searchListQuery['auditStatus'] = this.auditStatus
      }
      pageLiveGoods(this.searchListQuery).then((response) => {
        this.total = response.data.total
        this.goodsList = response.data.records
        if (response.data.dict) {
          this.dict = response.data.dict
        }
        this.listLoading = false
      })
    },
    handleSearch() {
      this.searchListQuery.currentPage = 1
      this.initGoodsList()
    },
    resetClick() {
      this.searchListQuery = {
        enterpriseId: this.getEnterpriseId(),
        supplierId: this.getSupplierId(),
        currentPage: 1,
        size: 10,
        title: ''
      }
      this.searchKeyword = ''
      this.initGoodsList()
    },
    beforeUpload(file) {
      this.fileChangeFlag = '0'
      const isJPG = file.type === 'image/jpeg'
      const isGIF = file.type === 'image/gif'
      const isPNG = file.type === 'image/png'
      const isBMP = file.type === 'image/bmp'

      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
      }
      this.fileLoading = true
      return isJPG || isBMP || isGIF || isPNG
    },
    handleUploadSuccess(res, file) {
      if (res.code === 101) {
        this.liveGoods.goodsImgUrl = res.data[0]
      } else {
        this.$message({
          type: 'error',
          message: res.msg
        })
        return false
      }
    },
    addLiveGoods(auditStatus) {
      if (
        this.priceType === '1' &&
        (!this.liveGoods.price || this.liveGoods.price <= 0)
      ) {
        this.$message.error('一口价不能为空且要大于0')
        return
      }
      if (
        this.priceType === '2' &&
        (!this.liveGoods.maxPrice || this.liveGoods.maxPrice <= 0)
      ) {
        this.$message.error('最低价不能为空且要大于0')
        return
      }
      if (
        this.priceType === '2' &&
        (!this.liveGoods.minPrice || this.liveGoods.minPrice <= 0)
      ) {
        this.$message.error('最高价不能为空且要大于0')
        return
      }
      if (
        this.priceType === '3' &&
        (!this.liveGoods.originalPrice || this.liveGoods.originalPrice <= 0)
      ) {
        this.$message.error('原价不能为空且要大于0')
        return
      }
      if (
        this.priceType === '3' &&
        (!this.liveGoods.nowPrice || this.liveGoods.nowPrice <= 0)
      ) {
        this.$message.error('现价不能为空且要大于0')
        return
      }
      if (
        !this.liveGoods.title ||
        this.liveGoods.title.length > 13 ||
        this.liveGoods.title.length < 3
      ) {
        this.$message.error('商品名称必须为3-14个汉字')
        return
      }
      this.liveGoods.priceType = this.priceType
      this.liveGoods.enterpriseId = this.getEnterpriseId()
      if (this.auditStatus === '3') {
        this.liveGoods.auditStatus = this.auditStatus
      } else {
        this.liveGoods.auditStatus = auditStatus
      }
      doApplyGoodsPrice(this.liveGoods).then((response) => {
        if (response.isError) return
        if (response.data === true) {
          this.saveGoods()
        } else {
          this.$confirm(
            '您设置的价格与商品当前价格不一致，可能导致直播间显示价格与商品详情页显示价格不一致，确认保存？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              this.saveGoods()
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
            })
        }
      })
    },
    saveGoods() {
      addLiveGoods(this.liveGoods).then((response) => {
        if (response.isError) return
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.liveGoodsVisible = false
        this.initGoodsList()
      })
    },
    // 编辑
    handleEdit(row, joinType) {
      if ([0, 2, 3].indexOf(row.auditStatus) === -1) return
      // if (row.auditStatus in [0, 2, 3] === false) return
      if (joinType === '2' || row.auditStatus === 2) {
        this.titleVisible = true
      } else {
        this.titleVisible = false
      }
      this.joinType = row.auditStatus === 2 ? '2' : joinType
      this.liveGoods = {}
      getLiveGoods(row.goodsId).then((response) => {
        if (response.isError) return
        this.liveGoods = response.data
        this.priceType = response.data.priceType
          ? response.data.priceType.toString()
          : '1'
        this.liveGoodsVisible = true
      })
    }
  }
}
</script>
<style lang="less" scoped>
.top-operate {
  margin-bottom: 0;
  height: 85px;
  background-color: #f7f8fa;
  display: flex;
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;
  label {
    font-weight: unset;
  }
  > div,
  .el-cascader {
    margin-right: 0px;
  }

  .el-input {
    width: 300px;
  }
}

.btn-search {
  height: 60px;
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 68px;
  height: 68px;
  display: block;
  padding: 1px;
  border: #efefef 1px solid;
}

.category-style {
  color: #3abbdb;
}

.gray-bar {
  background: #e4e4e4;
  padding: 20px;
  margin-bottom: 20px;
  width: 80%;
}
.tips {
  color: gray;
  font-size: 12px;
  line-height: 1.2;
  padding-top: 5px;
}
.goods-title {
  color: #155bd4;
  width: 50%;
  height: 45px;
  overflow: hidden;
  text-overflow: -o-ellipsis-lastline;
  text-overflow: ellipsis;
  white-space: normal;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  display: -webkit-box;
  text-align: justify;
}
</style>
